package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.OrderConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.mq.OrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.order.ao.OrderSubmitAo;
import com.atguigu.gulimall.order.ao.WareSkuLockAo;
import com.atguigu.gulimall.order.consumer.PayConstant;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WareFeignService;
import com.atguigu.gulimall.order.interceptor.OrderInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

@Slf4j
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    private ThreadLocal<OrderSubmitAo> orderThreadLocal=new ThreadLocal<>();

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public ConfirmVo confirmOrder() {
        ConfirmVo vo=new ConfirmVo();

        MemberRespVo memberRespVo = OrderInterceptor.threadLocal.get();

        //TODO :获取当前线程请求头信息(解决Feign异步调用丢失请求头问题)
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        //1.收货地址
        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            vo.setAddress(memberFeignService.getAddress(memberRespVo.getId()));
        }, threadPoolExecutor);

        //2.1查询用户购物车选中商品
        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            vo.setItems(cartFeignService.getCurrentCartItems());
        }, threadPoolExecutor).thenRunAsync(() -> {
            //2.2查询商品库存
            List<OrderItemVo> items = vo.getItems();
            List<Long> collect = items.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            R skuHasStock = wareFeignService.getSkuHasStock(collect);
            List<SkuStockVo> data = skuHasStock.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if (data != null) {
                Map<Long, Boolean> stockMap = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                vo.setStocks(stockMap);
            }
        }, threadPoolExecutor);

        //3.查询用户积分
        vo.setIntegration(memberRespVo.getIntegration());


        //5.防重复令牌
        String token = UUID.randomUUID().toString().replace("-","");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId(),token,30, TimeUnit.MINUTES);
        vo.setOrderToken(token);

        try {
            CompletableFuture.allOf(addressFuture,cartFuture).get();
        } catch (InterruptedException | ExecutionException e) {
            log.info("提交购物车异常");
            e.printStackTrace();
        }
        log.info("confirmOrder.vo={}", JSON.toJSONString(vo));
        return vo;
    }

    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitAo ao) {

        SubmitOrderResponseVo responseVo=new SubmitOrderResponseVo();
        orderThreadLocal.set(ao);


        //1.获取当前用户信息
        MemberRespVo memberRespVo = OrderInterceptor.threadLocal.get();
        responseVo.setCode(0);

        //2.验证令牌
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = ao.getOrderToken();

        Long execute = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()),
                orderToken);

        if (execute.equals(0L)){
            //3 临牌验证失败
            responseVo.setCode(1);
            return responseVo;
        }else {
            //4 验证成功
            OrderCreateTo order = createOrder();

            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = ao.getPayPrice();
            if ((Math.abs(payAmount.subtract(payPrice).doubleValue()))< 0.01){
                //5 金额比对成功
                saveOrder(order);

              //  error11();

                //6 检验库存
                WareSkuLockAo wareSkuLockAo=new WareSkuLockAo();
                wareSkuLockAo.setOrderSn(order.getOrder().getOrderSn());

                List<OrderItemEntity> OrderItemEntityList = order.getOrderItems();
                List<OrderItemVo> collect = OrderItemEntityList.stream().map(e -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(e.getSkuId());
                    orderItemVo.setCount(e.getSkuQuantity());
                    orderItemVo.setTitle(e.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockAo.setLocks(collect);
                R r = wareFeignService.lockStock(wareSkuLockAo);
                if (r.getCode().equals(0)){
                    //锁库存成功
                    responseVo.setOrder(order.getOrder());

                    //创建成功发送订单消息
                    rabbitTemplate.convertAndSend("order-event-exchange",
                            "order.create.order",
                            order.getOrder());
                    //删除购物车数据
                    return responseVo;
                }else {
                    //锁库存失败
                    String msg=(String) r.get("msg");
                    throw new NoStockException(msg);
                }
            }else {
                responseVo.setCode(2);
                return responseVo;
            }
        }
    }

    private void error11(){
        int i=10/0;
    }


    @Override
    public OderFareVo getFare(Long addrId) {
        OderFareVo fareVo=new OderFareVo();
        R r = memberFeignService.info(addrId);

        MemberAddressVo memberAddressVo = r.getData("memberReceiveAddress",new TypeReference<MemberAddressVo>() {});

        if (memberAddressVo != null) {
            String phone = memberAddressVo.getPhone();
            //截取用户手机号码最后一位作为我们的运费计算
            //1558022051
            String fare = phone.substring(phone.length() - 10, phone.length()-8);
            BigDecimal bigDecimal = new BigDecimal(fare);

            fareVo.setFare(bigDecimal);
            fareVo.setAddress(memberAddressVo);

            return fareVo;
        }
        return null;
    }

    @Override
    public OrderEntity getOrderStatus(String orderSn) {
        OrderEntity order = this.baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return  order;
    }

    @Override
    public void closeOrder(OrderEntity order) {
        OrderEntity orderEntity = this.getById(order.getId());

        if (orderEntity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())){
            OrderEntity updateEntity=new OrderEntity();
            updateEntity.setId(order.getId());
            updateEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(updateEntity);

            OrderTo OrderTo=new OrderTo();
            BeanUtils.copyProperties(orderEntity,OrderTo);

            rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",OrderTo);

        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo vo=new PayVo();
        vo.setOut_trade_no(orderSn);

        OrderEntity order = this.baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        BigDecimal payAmount = order.getPayAmount().setScale(2, RoundingMode.DOWN);
        vo.setTotal_amount(payAmount.toString());

        vo.setSubject("测试订单66");
        vo.setBody("好好");
        return vo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = OrderInterceptor.threadLocal.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId())
                        .orderByAsc("create_time"));
        List<OrderEntity> list = page.getRecords().stream().map(e -> {
            List<OrderItemEntity> itemEntityList = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", e.getOrderSn()));
            e.setOrderItemEntityList(itemEntityList);
            return e;
        }).collect(Collectors.toList());

        page.setRecords(list);

        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(PayAsyncVo asyncVo) {
        //保存订单流水信息
        PaymentInfoEntity paymentInfoEntity=new PaymentInfoEntity();
        paymentInfoEntity.setOrderSn(asyncVo.getOut_trade_no());
        paymentInfoEntity.setAlipayTradeNo(asyncVo.getTrade_no());
        paymentInfoEntity.setTotalAmount(new BigDecimal(asyncVo.getTotal_amount()));
        paymentInfoEntity.setSubject(asyncVo.getSubject());
        paymentInfoEntity.setPaymentStatus(asyncVo.getTrade_status());
        paymentInfoEntity.setCreateTime(new Date());
        paymentInfoEntity.setCallbackTime(asyncVo.getNotify_time());
        paymentInfoService.save(paymentInfoEntity);

        //修改订单状态
        String trade_status = asyncVo.getTrade_status();
        if (trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
            this.baseMapper.updateOrderStatus(asyncVo.getOut_trade_no(),OrderStatusEnum.PAYED.getCode(), PayConstant.ALIPAY);
        }
        return "success";
    }


    private void saveOrder(OrderCreateTo orderCreateTo){

        OrderEntity order = orderCreateTo.getOrder();
        order.setModifyTime(new Date());
        order.setCreateTime(new Date());
        this.baseMapper.insert(order);

        //订单项
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

     // 创建订单、订单项等信息
    private OrderCreateTo createOrder(){
        OrderCreateTo createTo=new OrderCreateTo();

        //1、生成订单号
        String orderSn = IdWorker.getTimeId();

        //2、构建订单
        OrderEntity orderEntity = buildOrder(orderSn);

        // 3、获取到所有的订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);

        // 4、计算价格、积分等相关信息
        computePrice(orderEntity,orderItemEntities);

        createTo.setOrder(orderEntity);
        createTo.setOrderItems(orderItemEntities);
        return createTo;
    }


    private void computePrice(OrderEntity orderItem,List<OrderItemEntity> entityList){
        BigDecimal total=new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");


        for (OrderItemEntity entity:entityList) {
            total=total.add(entity.getRealAmount());
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            gift = gift.add(new BigDecimal(entity.getGiftIntegration()));
            growth = growth.add(new BigDecimal(entity.getGiftGrowth()));
        }

        // 订单总额
        orderItem.setTotalAmount(total);
        // 应付总额
        orderItem.setPayAmount(total.add(orderItem.getFreightAmount()));
        orderItem.setCouponAmount(coupon);
        orderItem.setIntegrationAmount(integration);
        orderItem.setPromotionAmount(promotion);
        // 设置积分等信息
        orderItem.setIntegration(gift.intValue());
        orderItem.setGrowth(growth.intValue());
        orderItem.setDeleteStatus(0);//0 未删除


    }


    // * 构建所有订单项数据
    private  List<OrderItemEntity> buildOrderItems(String orderSn){
        List<OrderItemEntity> collect=null;
        List<OrderItemVo> currentCartItems = cartFeignService.getCurrentCartItems();
        if (!CollectionUtils.isEmpty(currentCartItems)){
               collect = currentCartItems.stream().map(cart -> {
                OrderItemEntity itemEntity = buildItem(cart);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
        }
        return collect;
    }

    private OrderItemEntity buildItem(OrderItemVo items){
        OrderItemEntity orderItemEntity = new OrderItemEntity();

        //1、商品的spu信息
        Long skuId = items.getSkuId();
        //获取spu的信息
        R spuInfo = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoData = spuInfo.getData("data", new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(spuInfoData.getId());
        orderItemEntity.setSpuName(spuInfoData.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoData.getBrandId().toString());
        orderItemEntity.setCategoryId(spuInfoData.getCatalogId());

        //2、商品的sku信息
        orderItemEntity.setSkuId(skuId);
        orderItemEntity.setSkuName(items.getTitle());
        orderItemEntity.setSkuPic(items.getImage());
        orderItemEntity.setSkuPrice(items.getPrice());
        orderItemEntity.setSkuQuantity(items.getCount());

        //使用StringUtils.collectionToDelimitedString将list集合转换为String
        String skuAttrValues = StringUtils.collectionToDelimitedString(items.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttrValues);

        //3、商品的优惠信息

        //4、商品的积分信息
        orderItemEntity.setGiftGrowth(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue());
        orderItemEntity.setGiftIntegration(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue());

        //5、订单项的价格信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);

        //当前订单项的实际金额.总额 - 各种优惠价格
        //原来的价格
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //原价减去优惠价得到最终的价格
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);

        return orderItemEntity;
    }

    //构建订单
    private OrderEntity buildOrder(String orderSn){
        MemberRespVo memberRespVo = OrderInterceptor.threadLocal.get();

        OrderEntity entity=new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(memberRespVo.getId());

        OrderSubmitAo orderSubmitAo = orderThreadLocal.get();
        // 1、获取运费 和 收货信息
        Long addressId = orderSubmitAo.getAddrId();
        OderFareVo fare = getFare(addressId);
        // 2、设置运费
        entity.setFreightAmount(fare.getFare());
        // 3、设置收货人信息
        entity.setReceiverPostCode(fare.getAddress().getPostCode());
        entity.setReceiverProvince(fare.getAddress().getProvince());
        entity.setReceiverRegion(fare.getAddress().getRegion());
        entity.setReceiverCity(fare.getAddress().getCity());
        entity.setReceiverDetailAddress(fare.getAddress().getDetailAddress());
        entity.setReceiverName(fare.getAddress().getName());
        entity.setReceiverPhone(fare.getAddress().getPhone());

        // 4、设置订单的相关状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);
        return entity;

    }

}